<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\Custom as ModelCustom;
use app\common\model\shop\Order;
use app\common\model\User;
use app\common\model\user\Alloca;
use app\common\model\user\Channel as UserChannel;
use app\common\model\user\Custom;
use app\common\model\user\Level;
use app\common\model\user\Pool;
use Exception;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 渠道接口
 */
class Channel extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    /**
     * @Author LK
     * @date: 2025-04-03 09:30:27
     * @ApiTitle (销售扶持数据)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function support()
    {
        $total = Alloca::where('channel', $this->auth->id)->count();
        $not_claim = Alloca::where('channel', $this->auth->id)->where('is_claim', 0)->count();
        $claim_num = Alloca::where('channel', $this->auth->id)->where('is_claim', 1)->count();
        $endtime = Alloca::where('channel', $this->auth->id)->where('is_claim', 0)->max('createtime');
        $endtime = $endtime ? $endtime + 2 * 86400 : 0;

        $enddate = Custom::where('channel', $this->auth->id)->where('is_apply', 0)->max('createtime');
        $enddate = $enddate ? $enddate + 18000 : 0;
        $custom_num = Custom::where('channel', $this->auth->id)->where('is_apply', 0)->count();

        $this->success("请求成功", compact('total', 'not_claim', 'claim_num', 'endtime', 'enddate', 'custom_num'));

        //total=总已分配多少人  not_claim=未分配销售人数  claim_num=已分配销售人数 custom_num=未分配客户人数 endtime=渠道最近时间   enddate=客户最近时间
    }
    /**
     * @Author LK
     * @date: 2025-03-24 10:06:36
     * @ApiTitle (销售公共池统计)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function statistics()
    {
        $total = Alloca::where('channel', $this->auth->id)->count();
        $num = Alloca::where('channel', $this->auth->id)->where('effective', '>=', 2000)->count();
        $proportion = $total > 0 ? bcmul($num / $total, 100, 0) : 0;
        $last_total = Alloca::where('channel', $this->auth->id)->whereTime('createtime', 'last month')->count();
        $last_number = Alloca::where('channel', $this->auth->id)->whereTime('createtime', 'last month')->where('effective', '>=', 2000)->count();
        $last_proportion = $last_total > 0 ? bcmul($last_number / $last_total, 100, 0) : 0;
        $fp_num = Alloca::where('channel', $this->auth->id)->where('is_claim', 1)->count();
        $last_fp_num = Alloca::where('channel', $this->auth->id)->whereTime('createtime', 'last month')->where('is_claim', 1)->count();
        $uids = [];
        User::digui($this->auth->id, $uids);
        $total_pay_fee = Order::whereIn('user_id', $uids)->where('status', '99')->sum('pay_fee');
        $channel_level = $this->auth->channel_level;
        $channel_level_info =  UserChannel::get($channel_level);
        if ($channel_level == 1) {
            $effective_performance = UserChannel::where('id', 1)->value('team_ach');
            $count = Order::whereIn('user_id', $uids)->where('status', '99')->group('user_id')->field('user_id,sum(pay_fee) as total_pay_fee')->having("total_pay_fee>{$effective_performance}")->count();
        }
        if ($channel_level == 2) {
            $count = User::where('channel', $this->auth->id)->where('is_channel', 1)->where('channel_level', '>', 0)->count();
        }
        if ($channel_level == 3) {
            $count = User::where('channel', $this->auth->id)->where('is_channel', 1)->where('channel_level', '>', 1)->count();
        }
        //转化率
        $number = Alloca::where('channel', $this->auth->id)->where('is_claim', 2)->count();
        $conversion_rate = $total > 0 ? bcmul($number / $total, 100, 0) : 0;
        $this->success("请求成功", compact('total', 'num', 'proportion', 'last_total', 'last_number', 'last_proportion', 'fp_num', 'last_fp_num', 'conversion_rate'));

        //total=总已分配多少人  num=总有效人数  proportion=总有效人数占比
        //last_total=上月分配多少人  last_number=上月有效人数  last_proportion=上月有效人数占比
    }
    /**
     * @Author LK
     * @date: 2025-03-21 10:23:15
     * @ApiTitle (渠道公共池)
     * @ApiMethod (GET)
    //  * @ApiParams (name="type", type="integer", required=true, sample="", description="0=无效,1=有效")
     * @ApiParams (name="class", type="integer", required=true, sample="", description="0=未分配,1=已分配")
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiParams (name="page", type="integer", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function channel_pool()
    {
        $params = request()->param();
        extract($params);
        $model = new Alloca();
        // if (isset($type)) {
        //     if ($type == 0) {
        //         $model->where('effective', '<', 2000);
        //     } else {
        //         $model->where('effective', '>=', 2000);
        //     }
        // }
        if ($class) {
            $model->where('is_claim', '>', 0);
        } else {
            $model->where('is_claim', 0);
        }
        $uids = $model->where('channel', $this->auth->id)->column('user_id');
        $lists =  Pool::whereIn('id', $uids)->order('id', 'desc')->paginate($limit ?? 10);
        foreach ($lists as $k => $v) {
            // $v->total = Order::where('user_id', $v['id'])->where('status', '>', 0)->count();
            // $v->assigninfo = User::get($v['parent_id']);
            $alloca = Alloca::where("user_id", $v['id'])->find();
            $v->endtime = $alloca->createtime + 2 * 86400;
            // $v->total_fee = Order::where('user_id', $v['id'])->where('status', '>', 0)->sum('pay_fee');
            // $v->effective =   $v->total_fee >= 2000 ? true : false;
            // $v->apply_time = $alloca->claimtime;
            // $v->apply_day = $v->apply_time ? date('Y-m-d', $v->apply_time) : '';
        }
        $this->success("请求成功", $lists);
    }

    /**
     * @Author LK
     * @date: 2025-03-21 10:29:03
     * @ApiTitle (搜索渠道下级)
     * @ApiMethod (GET)
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiParams (name="page", type="integer", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function search()
    {
        $params = request()->param();
        extract($params);
        $model = new User();
        $uids = [];
        User::digui($this->auth->id, $uids);
        if (isset($keywords) && $keywords) {
            $model->whereLike('mobile|nickname', "%" . $keywords . "%");
        }
        $lists = $model->whereIn('id', $uids)->paginate($limit ?? 10);
        foreach ($lists as $v) {
            $user_ids = Alloca::where('assign', $v['id'])->where('is_claim', 1)->select();
            $v->fp_num = count($user_ids);
            $num = 0;
            foreach ($user_ids as  $vv) {
                if ($vv['is_effective'] == true) {
                    $num++;
                }
            }
            $v->proportion = $v->fp_num > 0 ? bcmul($num / $v->fp_num, 100, 0) : 0;

            $total_list = Custom::alias('c')->where('c.channel', $this->auth->id)->field('id,(SELECT IF(sum(total_fee)>500,1,0) from fa_shop_order o where custom_id=c.custom_id and `status`>"0") as fee')->select();

            $total = count($total_list);
            $custom_num = array_sum(array_column($total_list, 'fee')) ?? 0;


            $v->fp_custom_num = count($total_list);
            $v->custom_proportion = $total > 0 ? bcmul($custom_num / $total, 100, 0) : 0;
        }
        $this->success("请求成功", $lists);
    }
    /**
     * @Author LK
     * @date: 2025-03-21 11:21:07
     * @ApiTitle (认领销售)
     * @ApiMethod (POST)
     * @ApiParams (name="user_ids", type="integer", required=true, sample="", description="销售")
     * @ApiParams (name="claim_id", type="integer", required=true, sample="", description="认领人")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function claim()
    {
        $user_ids = request()->param('user_ids');
        $claim_id = request()->param('claim_id');
        $claim = User::get($claim_id);
        if (!$claim) {
            $this->error("认领人不存在");
        }
        Db::startTrans();
        try {
            $alloca = Alloca::whereIn('user_id', $user_ids)->select();
            foreach ($alloca as $k => $v) {
                if ($v['is_claim']) {
                    exception("已认领");
                }
                $v->setAttr('acct_id', $claim->acct_id);
                $v->setAttr('is_claim', 1);
                $v->setAttr('claimtime', time());
                $v->setAttr('assign', $claim_id);
                $v->save();
            }
            if ($claim['is_channel'] == 1) {
                $channel = $claim_id;
            } else {
                $channel = $claim->channel;
            }
            Pool::whereIn('id', $user_ids)->update([
                'acct_id' => $claim->acct_id,
                'channel' => $channel,
                'claim' => $claim_id,
                'status' => 2,
            ]);
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success("认领成功");
    }
    /**
     * @Author LK
     * @date: 2025-10-16 11:00:03
     * @ApiTitle (已认领销售)
     * @ApiMethod (GET)
     * @ApiParams (name="is_claim", type="string", required=true, sample="", description="状态,1已认领,2已转化")
     * @ApiParams (name="page", type="string", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="string", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="string", required=true, description="")
     * @ApiReturn ({"code":1,"msg":"返回成功"})
     */
    public function claim_list()
    {
        $params = request()->param();
        extract($params);
        $lists = Alloca::with(['pool'])->whereIn('is_claim', $is_claim)->where('assign', $this->auth->id)->order('claimtime', 'desc')->paginate($limit ?? 10);
        foreach ($lists as $k => $v) {
            $v->total = Order::where('user_id', $v['uid'])->where('status', '>', 0)->count();
            $v->endtime = $v->createtime + 2 * 86400;
            $v->total_fee = Order::where('user_id', $v['id'])->where('status', '>', 0)->sum('pay_fee');
            $v->effective =   $v->total_fee >= 2000 ? true : false;
            $v->apply_time = $v->claimtime;
            $v->apply_day = $v->apply_time ? date('Y-m-d', $v->apply_time) : '';
        }
        $this->success("请求成功", $lists);
    }
    /**
     * @Author LK
     * @date: 2025-10-16 10:59:17
     * @ApiTitle (公共销售转化)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="string", required=true, sample="", description="销售ID")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="手机号")
     * @ApiParams (name="nickname", type="string", required=true, sample="", description="昵称")
     * @ApiParams (name="contact", type="string", required=true, sample="", description="紧急联系人")
     * @ApiParams (name="contact_phone", type="string", required=true, sample="", description="联系人电话")
     * @ApiParams (name="city", type="string", required=true, sample="", description="省市区")
     * @ApiParams (name="province_id", type="string", required=true, sample="", description="省ID")
     * @ApiParams (name="city_id", type="string", required=true, sample="", description="市ID")
     * @ApiParams (name="area_id", type="string", required=true, sample="", description="区ID")
     * @ApiParams (name="address", type="string", required=true, sample="", description="通讯地址")
     * @ApiParams (name="captcha", type="string", required=true, sample="", description="验证码")
     * @ApiReturnParams (name="code", type="string", required=true, description="")
     * @ApiReturn ({"code":1,"msg":"返回成功"})
     */
    public function convert()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['mobile', 'require', '手机号不能为空'],
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        if (!Sms::check($mobile, $captcha, 'trans') && $captcha != 8888) {
            $this->error(__('验证码错误'));
        }
        $sales = User::getByMobile($mobile);
        if ($sales) {
            $this->error("手机号已存在");
        }
        Db::startTrans();
        try {
            if (!$province_id || !$city_id || !$area_id) {
                $this->error('地址匹配失败');
            }
            $alloca = Alloca::get($id);
            $params['acct_id'] = $alloca->acct_id;
            $params['city'] = $city;
            $params['province_id'] = $province_id;
            $params['city_id'] = $city_id;
            $params['area_id'] = $area_id;
            $user = User::create($params, true);
            if (!$user) {
                exception("创建客户失败");
            }
            $alloca->setAttr('uid', $user->id);
            $alloca->setAttr('is_claim', 2);
            $alloca->setAttr('transtime', time());
            $alloca->save();
            Pool::whereIn('id', $alloca->user_id)->update([
                'status' => 3,
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("请求成功");
    }
    /**
     * @Author LK
     * @date: 2025-03-24 10:06:36
     * @ApiTitle (客户公共池统计)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function custom_statistics()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {
        }


        // $begin_time = date('Y-m-01 00:00:00',strtotime('-1 month')); 
        // $end_time = date("Y-m-d 23:59:59", strtotime(-date('d').'day')); 

        // $custom_ids = Custom::where('channel', $this->auth->id)->column('custom_id');

        $total_list = Custom::alias('c')->where('c.channel', $this->auth->id)->field('id,(SELECT IF(sum(total_fee)>500,1,0) from fa_shop_order o where custom_id=c.custom_id and `status`>"0") as fee')->select();

        $total = count($total_list);
        $num = array_sum(array_column($total_list, 'fee')) ?? 0;

        //Order::where('custom_id', 'in', $custom_ids)->where('status', '>', 0)->count();
        $proportion = $total > 0 ? bcmul($num / $total, 100, 0) : 0;


        $last_total_list = Custom::alias('c')->where('channel', $this->auth->id)->whereTime('createtime', 'last month')->field('id,(SELECT IF(sum(total_fee)>500,1,0) from fa_shop_order o where custom_id=c.custom_id and `status`>"0") as fee')->select();

        $last_total = count($last_total_list);
        $last_number = array_sum(array_column($last_total_list, 'fee')) ?? 0;

        // $last_number = Custom::alias('c')->where('c.channel', $this->auth->id)->whereTime('c.createtime', 'last month')->join('fa_shop_order o', 'c.custom_id=o.custom_id and o.status>0', 'left')->where('sum(o.total_fee)>=500')->group('c.id')->count('c.id');

        // $last_number = Order::whereTime('pay_time', 'last month')->where('custom_id', 'in', $custom_ids)->where('status', '>', 0)->count();

        $last_proportion = $last_total > 0 ? bcmul($last_number / $last_total, 100, 0) : 0;

        $fp_num = Custom::where('channel', $this->auth->id)->where('is_apply', 1)->count();
        $last_fp_num = Custom::where('channel', $this->auth->id)->whereTime('createtime', 'last month')->where('is_apply', 1)->count();

        $this->success("请求成功", compact('total', 'num', 'proportion', 'last_total', 'last_number', 'last_proportion', 'fp_num', 'last_fp_num'));
    }
    /**
     * @Author LK
     * @date: 2025-03-21 10:23:15
     * @ApiTitle (渠道公共池)
     * @ApiMethod (GET)
     * @ApiParams (name="type", type="integer", required=true, sample="", description="0=未认领,1=已认领")
     * @ApiParams (name="class", type="integer", required=true, sample="", description="0=未分配,1=已分配")
     * 
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiParams (name="page", type="integer", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function channel_custom_pool()
    {
        $params = request()->param();
        extract($params);
        $model = new ModelCustom();
        if (isset($keywords) && $keywords) {
            $model->where('mobile|name', 'like', "%" . $keywords . "%");
        }
        $where = [];

        if (isset($type)) {
            if ($type == 0) {
                $where['effective'] = ['<', 500];
            } else {
                $where['effective'] = ['>=', 500];
            }
        }

        if (isset($class)) {
            // $model->where('is_apply', $class);
            $uids = Custom::where('channel', $this->auth->id)->where('is_apply', $class)->where($where)->column('custom_id');
        } else {
            $uids = Custom::where('channel', $this->auth->id)->where($where)->column('custom_id');
        }

        if (count($uids)) {
            $model->whereIn('id', $uids);
        } else {
            $model->where('id', 0);
        }

        $lists = $model->order('id', 'desc')->paginate($limit ?? 10);
        foreach ($lists as $k => $v) {
            $v->total = Order::where('custom_id', $v['id'])->where('status', '>', 0)->count();
            $v->total_fee = Order::where('custom_id', $v['id'])->where('status', '>', 0)->sum('total_fee');
            $v->effective = $v->total_fee >= 500 ? true : false;
            $v->fp_user = User::where('id', $v->user_id)->field('id,nickname,mobile')->find() ?? '';
            $v->apply_time = Custom::where("custom_id", $v->id)->value('createtime') ?? 0;
            $v->apply_day = $v->apply_time ? date('Y-m-d', $v->apply_time) : '';
            $v->endtime = ($v->apply_time) + 18000;
        }
        $this->success("请求成功", $lists);
    }


    /**
     * @Author LK
     * @date: 2025-03-21 11:21:07
     * @ApiTitle (认领客户)
     * @ApiMethod (POST)
     * @ApiParams (name="custom_ids", type="integer", required=true, sample="", description="客户")
     * @ApiParams (name="claim_id", type="integer", required=true, sample="", description="认领人")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function claim_custom()
    {
        $custom_ids = request()->param('custom_ids');
        $claim_id = request()->param('claim_id');
        $claim = User::get($claim_id);
        // if (!$user) {
        //     $this->error("销售不存在");
        // }
        if (!$claim) {
            $this->error("认领人不存在");
        }
        Db::startTrans();
        try {
            $alloca = Custom::whereIn('custom_id', explode(',', $custom_ids))->select();
            foreach ($alloca as $k => $v) {
                if ($v['is_apply']) {
                    exception("已认领");
                }
                $v->setAttr('is_apply', 1);
                $v->setAttr('apply_time', time());
                $v->setAttr('assign', $claim_id);
                $v->save();
            }
            ModelCustom::whereIn('id', $custom_ids)->update([
                'user_id' => $claim_id
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("认领成功");
    }
}
